<template>
  <div class="newsbulletin">
    <Header title="新闻公告" />
    <div class="mui-content">
      <div
        id="slider"
        v-if="!isEmpty(listData)"
        class="mui-slider mui-fullscreen"
      >
        <div
          id="sliderSegmentedControl"
          class="mui-scroll-wrapper mui-slider-indicator mui-segmented-control mui-segmented-control-inverted"
        >
          <div class="mui-scroll newsbulletin-nav">
            <a
              v-for="(item, index) in nav_list"
              :key="index"
              :class="{' mui-active': index === 0}"
              :href="`#${item.id}`"
              @tap="initData(item)"
              class="mui-control-item newsbulletin-nav-a"
            >{{ item.name }}</a>
          </div>
        </div>

        <div
          class="mui-slider-group"
          style="margin-top: 10px;"
        >
          <div
            v-for="({ id }, index) in nav_list"
            :id="id"
            :key="index"
            :class="{' mui-active': index === 0}"
            class="mui-slider-item mui-control-content"
            style="border:0px;background: #FFFFFF;"
          >
            <div
              v-if="dataFlags[id]"
              class="noData"
            >
              暂无数据
            </div>
            <div
              class="mui-scroll-wrapper list"
            >
              <div class="mui-scroll">
                <ul class="mui-table-view">
                  <li
                    v-for="(item, index) in listData[id]"
                    :key="index"
                    @tap="clickInfo(item)"
                    class="mui-table-view-cell"
                  >
                    <div
                      :style="{ background : item.SY_FUNCEDIT=='2' ? '#FF3D3D' : '#A9ABA9'}"
                      class="newsbulletin-title-circle"
                    />
                    <div class="newsbulletin-left">
                      <div
                        :style="{ color : item.SY_FUNCEDIT=='2' ? '#333' : 'grey'}"
                        class="newsbulletin-title"
                        style="-webkit-box-orient: vertical;"
                      >
                        {{ item.NOTICE_TITLE }}
                      </div>
                      <p class="newsbulletin-info">
                        {{ item.SY_CREATETIME }}
                        <Icon
                          type="jeicon-eye"
                          size="xxxs"
                          style="margin-left:9px;font-size: 12px;"
                        />
                        ({{ item.NOTICE_YDL }})
                        <Icon
                          type="jeicon jeicon-thumbs-up-o"
                          size="xxxs"
                          style="margin-left:9px;"
                        />
                        ({{ item.NOTICE_DZL }})
                      </p>
                    </div>
                    <div
                      v-if="item.NOTICE_FM!=''"
                      class="newsbulletin-img_wrp"
                    >
                      <img
                        :src="item.NOTICE_FM"
                        class="newsbulletin-img"
                      >
                    </div>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { AllHtmlEntities } from 'html-entities';
import isEmpty from 'lodash/isEmpty';
import Icon from '@/components/icon';
import Header from '@/components/header';
import {
  getNews, readFuncEdit, doUpdate, getById, getNav,
} from './actions/action';

const { decode } = AllHtmlEntities;

export default {
  name: 'NewsBulletin',
  components: {
    Icon, Header,
  },
  data() {
    return {
      nav_list: [],
      listData: {},
      checkData: {},
      currentPage: 1,
      queryColumns: 'NOTICE_TITLE,SY_CREATETIME,NOTICE_YDL,NOTICE_DZL,NOTICE_FM,NOTICE_DZUSERIDS,JE_SYS_NOTICE_ID',
      pullRefreshWrapper: [],
      dataFlags: {
        item1mobile: false,
        item2mobile: false,
        item3mobile: false,
        item4mobile: false,
        item5mobile: false,
        item6mobile: false,
      },
    };
  },
  created() {
    const that = this;
    that.initNavData();
    // 监控是否调用了点赞方法
    window.addEventListener('doUpdateDzl', (e) => {
      const checkId = that.checkData.id;
      // 同步更新首页的点赞数和点赞人的ids
      that.listData[checkId].map((item, index) => {
        if (item.JE_SYS_NOTICE_ID === e.detail.id) {
          that.listData[checkId][index].NOTICE_DZL = e.detail.NOTICE_DZL;
          that.listData[checkId][index].NOTICE_DZUSERIDS = e.detail.NOTICE_DZUSERIDS;
        }
        return null;
      });
    });
    window.addEventListener('clickInfoaddcount', (e) => {
      const checkId = that.checkData.id;
      that.listData[checkId].map((item, index) => {
        if (item.JE_SYS_NOTICE_ID === e.detail.id) {
          that.listData[checkId][index].NOTICE_YDL++;
        }
        return null;
      });
    });
    window.addEventListener('detailBack', async (e) => {
      await that.initData(that.checkData);
    });
  },
  mounted() {
    // 阻尼系数
    mui('.mui-scroll-wrapper.list').scroll({
      bounce: false,
      scrollX: false,
      scrollY: true,
      indicators: false,
    });
  },
  methods: {
    isEmpty,
    // 加载导航栏的数据
    async initNavData() {
      const data = await getNav({
        tableCode: 'JE_CORE_DICTIONARY',
        DICTIONARY_DDCODE: 'JE_SYS_NOTICETYPE',
      });
      data.forEach(({ code, text }) => {
        const newId = `item${code.split('0')[1]}mobile`;
        this.nav_list.push({ name: text, type: code, id: newId });
      });
      await this.initData(this.nav_list[0]);
      this.$nextTick(() => {
        this.initRefresh();
        mui('#sliderSegmentedControl').scroll({
          bounce: true,
          indicators: false,
        });
      });
    },

    // 新闻公告数据
    initData(item) {
      // 当前选中的模块的数据
      const that = this;
      this.checkData = item;
      const { type, id } = item;
      const params = {
        tableCode: 'JE_SYS_NOTICE',
        whereSql: `AND NOTICE_QY='1' AND NOTICE_NOTICETYPE_CODE = ${type}`,
        orderSql: 'ORDER BY SY_CREATETIME DESC',
        j_query: JE.encode({
          custom: [
            { type: '=', code: 'NOTICE_NOTICETYPE_CODE', value: type },
            { type: '=', code: 'NOTICE_QY', value: '1' },
          ],
          order: [
            { type: 'desc', code: 'SY_CREATETIME' },
          ],
        }),
        funcCode: 'JE_SYS_NOTICE',
        queryColumns: 'NOTICE_TITLE,SY_CREATETIME,NOTICE_YDL,NOTICE_DZL,NOTICE_FM,NOTICE_DZUSERIDS,JE_SYS_NOTICE_ID',
        funcEdit: true,
        page: 1,
        start: 0,
        limit: 10,
      };
      return getNews(params).then((data) => {
        const { rows } = data;
        if (JE.isEmpty(rows)) {
          that.dataFlags[id] = true;
        }
        // 转载数据
        this.$set(this.listData, id, [
          ...rows.map(({
            NOTICE_FM, SY_CREATETIME, NOTICE_YDL, NOTICE_DZL, ...other
          }) => ({
            // NOTICE_CONTEXT_IMG: this.HTMLDecode(NOTICE_CONTEXT, true).map(x =>
            // x.replace(/.*src="([^"]*)".*/, "$1")
            // ),
            // NOTICE_CONTEXT: decode(NOTICE_CONTEXT),
            NOTICE_FM: this.getFileUrl(NOTICE_FM),
            SY_CREATETIME: SY_CREATETIME.split(' ')[0],
            NOTICE_YDL: this.getNumber(NOTICE_YDL),
            NOTICE_DZL: this.getNumber(NOTICE_DZL),
            ...other,
          })),
        ]);
        mui('.mui-slider').slider();
      });
    },
    // 转换html
    HTMLDecode(text, img) {
      let temp = document.createElement('div');
      temp.innerHTML = text;
      const output = temp.innerText || temp.textContent;
      temp = null;
      if (img) {
        return output.match(/<img [^>]*src="[^"]*"[^>]*>/gm) || [];
      }
      return output;
    },
    // 点击进详情
    async clickInfo(item) {
      const that = this;
      const byIdData = await this.getByIdData(item);
      byIdData.NOTICE_CONTEXT = decode(byIdData.NOTICE_CONTEXT);
      byIdData.NOTICE_YDL = this.getNumber(byIdData.NOTICE_YDL);
      byIdData.NOTICE_DZL = this.getNumber(byIdData.NOTICE_DZL);
      // 如果未读执行方法(2未读0已读)
      if (item.SY_FUNCEDIT === '2') {
        readFuncEdit({
          tableCode: 'JE_SYS_NOTICE',
          funcCode: 'JE_SYS_NOTICE',
          pkValue: byIdData.JE_SYS_NOTICE_ID,
        }).then((data) => {
          if (data.success) {
            JE.refreshBadge({ badge: -1, code: 'JE-PLUGIN-NEWS', type: 'NOTICE' });
          } else {
            mui.toast(data.obj);
          }
        });
      }
      doUpdate({
        tableCode: 'JE_SYS_NOTICE',
        NOTICE_YDL: parseInt(byIdData.NOTICE_YDL) + 1,
        JE_SYS_NOTICE_ID: byIdData.JE_SYS_NOTICE_ID,
      }).then((data) => {
        if (data.success) {
          byIdData.NOTICE_YDL = this.getNumber(data.obj.NOTICE_YDL);
          byIdData.SY_FUNCEDIT = '0';
          // item.NOTICE_YDL = this.getNumber(data.obj.NOTICE_YDL);
          item.SY_FUNCEDIT = '0';
          this.$router.push({
          path: '/JE-PLUGIN-NEWS/info',
          query: {
            id: '__info',
            title: this.checkData.name,
            byIdData: byIdData
          },
        });
          // JE.openWindow({
          //   url: 'pages_info_index.html',
          //   id: '__info',
          //   title: this.checkData.name,
          //   extras: {
          //     byIdData,
          //   },
          // });
        } else {
          mui.toast('阅读失败!');
        }
      });
    },
    // 获取图片路径
    getFileUrl(url) {
      if (url != '' && url != null) {
        const newUrl = 'http://crm-private.oss-cn-beijing.aliyuncs.com';
        return newUrl + url.split('*')[1];
      }
      return '';
    },
    // 根据ID查询数据
    getByIdData(item) {
      return getById({
        tableCode: 'JE_SYS_NOTICE',
        pkValue: item.JE_SYS_NOTICE_ID,
      });
    },
    // 循环初始化所有下拉刷新，上拉加载。
    initRefresh() {
      const that = this;
      mui('.mui-slider').slider();
      const pullRefreshWrapper = Array.from(document.querySelectorAll('.mui-scroll-wrapper.list'));
      this.pullRefreshWrapper = pullRefreshWrapper.map(
        pullRefreshEl => mui(pullRefreshEl).pullRefresh4HTML({
          // 下拉刷新
          down: {
            async callback() {
              const self = this;
              await that.initData(that.checkData);
              self.endPulldownToRefresh();
              self.refresh(true);
              that.currentPage = 1;
              mui.toast('刷新成功');
            },
          },
          // 上拉加载
          up: {
            auto: false,
            offset: 1000, // 距离底部高度(到达该高度即触发)
            show: true,
            contentinit: '上拉显示更多',
            contentdown: '上拉显示更多',
            contentrefresh: '正在加载...',
            contentnomore: '没有更多数据了',
            callback() {
              const self = this;
              const checkTypeId = that.checkData.id;
              that.currentPage++;
              const paramObj = {
                tableCode: 'JE_SYS_NOTICE',
                whereSql: `AND NOTICE_QY='1' AND NOTICE_NOTICETYPE_CODE = ${
                  that.checkData.type
                }`,
                orderSql: 'ORDER BY SY_CREATETIME DESC',
                j_query: JE.encode({
                  custom: [
                    { type: '=', code: 'NOTICE_NOTICETYPE_CODE', value: that.checkData.type },
                    { type: '=', code: 'NOTICE_QY', value: '1' },
                  ],
                  order: [
                    { type: 'desc', code: 'SY_CREATETIME' },
                  ],
                }),
                funcCode: 'JE_SYS_NOTICE',
                funcEdit: true,
                queryColumns: 'NOTICE_TITLE,SY_CREATETIME,NOTICE_YDL,NOTICE_DZL,NOTICE_FM,NOTICE_DZUSERIDS,JE_SYS_NOTICE_ID',
                page: that.currentPage,
                start: that.currentPage * 10 - 10,
                limit: 10,
              };
              getNews(paramObj).then((data) => {
                if (data.success === false) {
                  mui.toast('数据查询失败');
                  return false;
                }
                // 转html和图片路径
                data.rows.forEach((item) => {
                  item.NOTICE_FM = that.getFileUrl(item.NOTICE_FM);
                  item.SY_CREATETIME = item.SY_CREATETIME.split(' ')[0];
                  item.NOTICE_YDL = that.getNumber(item.NOTICE_YDL);
                  item.NOTICE_DZL = that.getNumber(item.NOTICE_DZL);
                });
                // 禁用上拉加载
                if (that.currentPage > 1) {
                  const bottomtips = document.getElementById(checkTypeId).getElementsByClassName('mui-pull');
                  if (bottomtips != '' && bottomtips != undefined) {
                    bottomtips[1].style.display = '';
                  }
                }
                if (data.rows.length <= 0) {
                  self.endPullupToRefresh(true);
                  return false;
                }
                self.endPullupToRefresh(false);
                // 数据拼接
                that.$set(
                  that.listData,
                  checkTypeId,
                  that.listData[checkTypeId].concat(data.rows)
                );
              });
            },
          },
        })
      );
      // 左右滑动
      document.getElementById('slider').addEventListener('slide', async ({ detail: { slideNumber } }) => {
        const num = slideNumber + 1;
        // 根据滑动的type获取选中nav的数据
        const type = `0${num}`;
        let item;
        that.nav_list.forEach((list) => {
          if (list.type === type) {
            item = list;
          }
        });
        this.checkData = item;
        this.currentPage = 1;
        await that.initData(item);
        const currentPullRefresh = this.pullRefreshWrapper[slideNumber];
        currentPullRefresh.refresh(true);
        mui(currentPullRefresh.element.parentNode).scroll().refresh();
        const bottomtips = document.getElementById(this.checkData.id).getElementsByClassName('mui-pull');
        bottomtips[1].style.display = 'none';
        // this.pullRefreshWrapper[slideNumber].pullDownLoading();
      });
    },
    // 数字装换
    getNumber(num) {
      let number = parseInt(num);
      if (number >= 10000) {
        number = `${parseFloat(number / 10000).toFixed(1)}万`;
      }
      return number;
    },
  },
};
</script>
<style lang="less" scoped>
@import "~@/theme/index.less";
.newsbulletin {
  .noData {
    position: absolute;
    top: 50%;
    width: 100%;
    left: 0;
    margin-top: -20 * @hd;
    text-align: center;
    font-size: 20 * @hd;
    color: #bebebe;
  }
  .newsbulletin-img_wrp {
    width: 113 * @hd;
    height: 68 * @hd;
    overflow: hidden;
    margin-left: 10 * @hd;
    .newsbulletin-img {
      // height: 58 * @hd !important;
      // width: 98 * @hd !important;
      width: 100%;
      height: 100%;
      // margin-left: 15 * @hd;
    }
  }
  .newsbulletin-nav {
    color: #3f3f3f;
    font-size: 16 * @hd;
    height: 44 * @hd;
    background: #FFFFFF;
    .newsbulletin-nav-a{
      font-size: 16 * @hd;
      border-bottom: 1px solid transparent;
      height: 44 * @hd;
      line-height: 44 * @hd;
    }
  }
  .newsbulletin-title {
    line-height: 22 * @hd;
    height: 44 * @hd;
    font-size: 16 * @hd;
    color: #3f3f3f;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }
  .newsbulletin-title-circle{
      width:4  * @hd;
      height:4  * @hd;
      background:rgba(255,61,61,1);
      border-radius:50%;
      display: inline-block;
      margin-top: 3* @hd;
      margin-right: 4* @hd;
      flex-shrink: 0;
    }
  .newsbulletin-info {
    font-size: 14 * @hd;
    color: #a9aba9;
    font-weight: 400;
    position: absolute;
    bottom: 0;
    left: 0;
    height: 20 * @hd;
  }
  .mui-table-view-cell {
    display: flex;
    padding: 10px 15* @hd;
    .newsbulletin-left {
      flex: 1;
      position: relative;
      padding-bottom: 25 * @hd;
    }
    &:after {
      background-color: #F5F5F5;
      height: 2 * @hd;
    }
  }
}
</style>
<style lang="less">
@import "~@/theme/index.less";
html,
body {
  background-color:#F8F8F8 !important;
}
.mui-fullscreen{
  top: 45 * @hd;
}
.mui-bar ~ .mui-content .mui-fullscreen {
  top: 44 * @hd;
  height: auto;
}
.mui-pull-top-tips {
  position: absolute;
  top: -20 * @hd;
  left: 50%;
  margin-left: -25 * @hd;
  width: 40 * @hd;
  height: 40 * @hd;
  border-radius: 100%;
  z-index: 1;
}
.mui-bar ~ .mui-pull-top-tips {
  top: 24 * @hd;
}
.mui-pull-top-wrapper {
  width: 42 * @hd;
  height: 42 * @hd;
  display: block;
  text-align: center;
  background-color: #efeff4;
  border: 1 * @hd solid #ddd;
  border-radius: 25 * @hd;
  background-clip: padding-box;
  box-shadow: 0 4 * @hd 10 * @hd #bbb;
  overflow: hidden;
}
.mui-pull-top-tips.mui-transitioning {
  -webkit-transition-duration: 200ms;
  transition-duration: 200ms;
}
.mui-pull-top-tips .mui-pull-loading {
  /*-webkit-backface-visibility: hidden;
      -webkit-transition-duration: 400ms;
      transition-duration: 400ms;*/

  margin: 0;
}
.mui-pull-top-wrapper .mui-icon,
.mui-pull-top-wrapper .mui-spinner {
  margin-top: 7 * @hd;
}
.mui-pull-top-wrapper .mui-icon.mui-reverse {
  /*-webkit-transform: rotate(180deg) translateZ(0);*/
}
.mui-pull-bottom-tips {
  text-align: center;
  background-color: #efeff4;
  font-size: 15 * @hd;
  line-height: 40 * @hd;
  color: #777;
}
.mui-pull-top-canvas {
  overflow: hidden;
  background-color: #fafafa;
  border-radius: 40 * @hd;
  box-shadow: 0 4 * @hd 10 * @hd #bbb;
  width: 40 * @hd;
  height: 40 * @hd;
  margin: 0 auto;
}
.mui-pull-top-canvas canvas {
  width: 40 * @hd;
}
.mui-slider-indicator.mui-segmented-control {
  background-color: #ffffff;
}
// 修改tab标签高度
.mui-segmented-control.mui-scroll-wrapper {
  height: 45 * @hd;
}
.mui-slider .mui-segmented-control.mui-segmented-control-inverted .mui-control-item.mui-active {
  border-bottom: 1px solid #007aff !important;
}
.mui-fullscreen .mui-segmented-control~.mui-slider-group {
  top: 44 * @hd;
}
.mui-scrollbar {
  display: none !important;
}
</style>
